import React from 'react'
import { createStore } from 'redux'
import { useSelector, useDispatch, Provider } from 'react-redux'
import { gen } from '../common/data-gen'
import { Buttons } from '../common/buttons.jsx'
import { Table } from '../common/table.jsx'

const store = createStore(function(state = {}, action) {
  switch (action.type) {
    case 'RENDER':
    case 'UPDATE':
      return { ...state, data: action.data }
  }
})

const DATA = gen()

export default function App() {
  return (
    <Provider store={store}>
      <MyComponent />
    </Provider>
  )
}

function MyComponent() {
  const data = useSelector((state) => {
    return state ? state.data : []
  })
  const dispatch = useDispatch()
  const update = () => {
    const next = data.map((item, i) => {
      if (i === 10) {
        return { ...item, price: (Math.random() * 100).toFixed(2) }
      }
      else if (i === 1001) {
        return { ...item, weight: (Math.random() * 100).toFixed(2) }
      }
      else {
        return item
      }
    })
    dispatch({ type: 'UPDATE', data: next })
  }
  return (
    <div>
      <div>
        <Buttons onRender={() => dispatch({ type: 'RENDER', data: DATA })} onUpdate={update} />
      </div>
      <div>
        <Table data={data} />
      </div>
    </div>
  )
}
